﻿using NewProcessGuarder.toolFunc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Linq;
using System.Text;

namespace NewProcessGuarder.core
{
    [Serializable]
    public class LogGuarder : AppGuarder, ILogGuarder
    {
        private string logFilePath;
        public string LogFilePath
        {
            get { return logFilePath; }
            set {
                logFilePath = value;
                OnPropertyChanged("LogFilePath");
            }
        }

        private int writeInterval = 1000 * 60 * 2;
        
        public int WriteInterval
        {
            get { return writeInterval; }
            set {
                writeInterval = value;
                OnPropertyChanged("WriteInterval");
            }
        }
        
        public DateTime LastWriteTime
        {
            get
            {
                if (File.Exists(logFilePath))
                    return (new FileInfo(logFilePath)).LastWriteTime;
                else
                    return Convert.ToDateTime("1900-01-01 00:00");
            }
        }
        
        public LogGuarder()
            : base()
        {

        }
        
        public override void TimerHandle(object state)
        {
            try
            {
                switch (this.OperType)
                {
                    case OperationType.ProcessGuard:
                        ProcessEngine();
                        break;
                    case OperationType.StartPro:
                        break;
                    case OperationType.StopPro:
                        break;
                    default:
                        ProcessEngine();
                        break;
                }

                //Process,IECache,FindWindowBug
                //switch (this.OperType)
                //{
                //    case OperationType.ProcessGuard:
                //        ProcessEngine();
                //        break;
                //    case "":
                //        IECacheEngin();
                //        break;
                //    case "FindWindowBug":
                //        FindWindowBug();
                //        break;
                //    default:
                //        {
                //            ProcessEngine();
                //            break;
                //        }
                //}
                
            }
            catch { }
        }

        private void ProcessEngine()
        {
            if (!File.Exists(AppPath)) throw new FileNotFoundException("应用程序不存在");

            if (BeginTime != null && EndTime != null)
            {
                TimeSpan tsBeginToEnd = EndTime.Value.Subtract(BeginTime.Value);

                if (BeginTime == null && EndTime == null)
                {
                    BeginTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + BeginTime.Value.ToShortTimeString());
                    EndTime = BeginTime.Value.Add(tsBeginToEnd);
                }
                else if (DateTime.Now > BeginTime) //重新计算时间
                {
                    BeginTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + BeginTime.Value.ToShortTimeString());
                    EndTime = BeginTime.Value.Add(tsBeginToEnd);
                }

                if (DateTime.Now > BeginTime && DateTime.Now < EndTime)
                {
                    goto loop;
                }
                else
                {
                    if (ProcessFunc.ProcessExists(AppPath))
                    {
                        ProcessFunc.KillProcessByPath(AppPath);

                        if (!string.IsNullOrEmpty(KillOtherPath))
                        {
                            var list = KillOtherPath.Split('^');
                            foreach (var path in list)
                            {
                                if (string.IsNullOrEmpty(path))
                                    continue;

                                ProcessFunc.KillProcessByPath(path);
                            }
                        }
                    }

                }

                return;
            }

            loop:
            if (string.IsNullOrEmpty(logFilePath) || !File.Exists(logFilePath))
            {
                if (!ProcessFunc.ProcessExists(AppPath))
                    ProcessFunc.StartProcessByPath(AppPath);
            }
            else
            {
                DateTime currentTime = DateTime.Now;

                TimeSpan tsNow = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan tsFile = new TimeSpan(LastWriteTime.Ticks);

                TimeSpan ts = tsNow.Subtract(tsFile).Duration();

                if (ts.TotalSeconds - writeInterval / 1000 > 0)
                {
                    ProcessFunc.RestartApplication(AppPath);
                }
            }
        }

        private void IECacheEngin()
        {
            SystemTool.RunCmd("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8");
        }

        private void FindWindowBug()
        {
            var list = KillOtherPath.Split('^');
            if (list.Length <= 1)
                return;

            //AppPath 在FindWindowBug 为名称
            IntPtr ParenthWnd = Native.FindWindow(null, list[0]);
            if (ParenthWnd != IntPtr.Zero)
            {
                IntPtr WndCli6 = Native.GetWindow(ParenthWnd, 6);
                if (WndCli6 != IntPtr.Zero && WndCli6 != ParenthWnd)
                    windowClient(WndCli6, list);
            }
        }

        private void windowClient(IntPtr WndCli, string[] list)
        {
            StringBuilder sb = new StringBuilder();
            Native.GetWindowText(WndCli, sb, 255);
            foreach (var str in list)
            {
                if (str == sb.ToString())
                    ProcessFunc.KillProcessByPath(AppPath);
            }
        }

        public override string ToString()
        {
            return this.Name;
        }

    }
}